package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.TransactionInfoDao;
import com.framework.dto.AcceptKaYouDTO;
import com.framework.entity.flow.FlowAccount;
import com.framework.entity.log.LogAccount;
import com.framework.entity.log.LogTranInfo;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.sys.SysAgentInfo;
import com.framework.entity.sys.SysDept;
import com.framework.entity.sys.SysLvRate;
import com.framework.entity.ter.TerLishuaVip;
import com.framework.entity.ter.TerMerchantReport;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.entity.tran.*;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.service.*;
import com.framework.utils.DateUtils;
import com.framework.utils.excel.ExcelUtil;
import com.framework.utils.httpClient.HttpClean;
import com.framework.utils.string.DateStrUtils;
import com.framework.utils.string.StringUtil;
import com.framework.utils.verified.MathUtils;
import com.framework.validator.Assert;
import com.framework.view.*;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

@Transactional(rollbackFor = Exception.class)
@Service("transactionInfoService")
@Slf4j
public class TransactionInfoServiceImpl extends ServiceImpl<TransactionInfoDao, TranTransactionInfo> implements TransactionInfoService {

    //计算分润时所需要扣除的费率
    private final static BigDecimal DIVIDENUM = new BigDecimal("10000");

    @Autowired
    private AgentService agentService;
    @Autowired
    private TerminalInfoService terminalInfoService;

    @Autowired
    private BenefitDayService benefitDayService;
    @Autowired
    private BenefitInfoService benefitInfoService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private TransactionInputLishuaService transactionInputLishuaService;
    @Autowired
    private FlowCardService flowCardService;
    @Autowired
    private FlowActivService flowActivService;
    @Autowired
    private FlowAccountService flowAccountService;
    @Autowired
    private DistribuService distribuService;

    @Autowired
    private TransactionInputService transactionInputService;

    @Autowired
    private StarposTranInputService starposTranInputService;

    @Autowired
    private LogTranInfoService logTranInfoService;
    @Autowired
    private TranTerBenefitDayService tranTerBenefitDayService;

    @Autowired
    private TranOrderService tranOrderService;

    @Autowired
    private LvRateService lvRateService;

    @Autowired
    private TranTerBenefitInfoService tranTerBenefitInfoService;


    @Autowired
    private TerLishuaVipService terLishuaVipService;


    @Override
    public Map<String, Object> getIndexTransaction(String token, Integer type) {
        if (StringUtils.isBlank(token) || type == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        //type参数： 1-昨天 2-本月
        Map<String, Object> map = new HashMap<>(5);
        //查询缓存中所属人信息
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //团队交易
        BigDecimal teamAmount = queryTransactionSum(agentId, type, 2);

        map.put("teamAmountSum", MathUtils.formatToMoney(MathUtils.formatToNumber(teamAmount)));
        //团队新增
        int agentAddCount = agentService.queryAgentAddCount(agentId, type, 2);
        map.put("agentAddCount", agentAddCount);
        //商户报备新增
        int merchantAddCount = merchantService.queryMerchantCount(agentId, type, 2);
        map.put("merchantAddCount", merchantAddCount);
        //团队采购
        int byTerminalCount = tranOrderService.queryByTerminalCount(agentId, type, 2);
        map.put("byTerminalCount", byTerminalCount);
        //团队激活
        int terminalActCount = terminalInfoService.queryActivationCount(agentId, type, 2);
        map.put("terminalActCount", terminalActCount);
        return map;
    }

    @Override
    public BigDecimal queryTransactionSum(Long agentId, int type, Integer isOwn) {
        BigDecimal amount = baseMapper.queryTransactionSum(agentId, type, isOwn);
        return amount;
    }

    @Override
    public Map<String, Object> getIncomeMap(String token) {
        Assert.isBlank(token, "token不能为空");
        Map<String, Object> map = new HashMap<>();
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agentId);
        Assert.isNull(agentInfo, "未查询到代理商基础信息");
        //可提金额
        map.put("availableAmount", agentInfo.getAvailableAmount());
        //本月
        String lastMonth = StringUtil.getLast12Months(1);
        //上个月
        String lastTwoMonth = StringUtil.getLast12Months(2);
        //上个月、上上个月自营交易分润
        DividedSumDto selfMap = benefitDayService.queryTransMonthSum(lastMonth, lastTwoMonth, agentId, "self_amount");
        map.put("selfMap", nextEstimate(selfMap.getLastAmount(), selfMap.getLastTwoAmount()));
        //上个月、上上个月团队交易分润
        DividedSumDto teamMap = benefitDayService.queryTransMonthSum(lastMonth, lastTwoMonth, agentId, "team_amount");
        map.put("teamMap", nextEstimate(teamMap.getLastAmount(), teamMap.getLastTwoAmount()));
        //累计提现提现明细 总收益-剩余余额
        //BigDecimal taskAmount = flowTaskService.getTaskAmount(agentId);
        BigDecimal taskAmount = agentInfo.getTotalAmount().subtract(agentInfo.getAvailableAmount());
        map.put("taskAmount", taskAmount);
        //商户拓展 自营
        BigDecimal selfAmount = benefitDayService.getThisMonthAmount(agentId, 1);
        map.put("selfAmount", selfAmount);
        //团队推广 团队
        BigDecimal teamAmount = benefitDayService.getThisMonthAmount(agentId, 2);
        map.put("teamAmount", teamAmount);
        //推荐办卡
        BigDecimal cardAmount = flowCardService.getThisMonthAmount(agentId);
        map.put("cardAmount", cardAmount);
        //活动奖励
        map.put("activityAmount", new BigDecimal("0.00"));
        //其它奖励
        BigDecimal otherAmount = flowAccountService.queryOtherAmount(agentId);
        map.put("otherAmount", otherAmount);
        //激活返现
        BigDecimal activAmount = flowActivService.getThisMonthAmount(agentId);
        map.put("activAmount", activAmount);
        //本月分润示意图
        Map<String, Object> pieAmountMap = new HashedMap();
        pieAmountMap.put("selfAmount", selfAmount); //自营
        pieAmountMap.put("teamAmount", teamAmount); //团队
        pieAmountMap.put("cardAmount", cardAmount); //信用卡
        pieAmountMap.put("activAmount", activAmount); //激活返现
        map.put("pieAmountMap", pieAmountMap);
        return map;
    }

    @Override
    public Map<String, Object> getExpandMap(String token, Integer type) {
        Assert.isBlank(token, "token不能为空");
        Map<String, Object> map = new HashMap<>();
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //自营
        ExpandDto personal = new ExpandDto();
        if (type == null) {
            type = 2;
        }
        //交易
        BigDecimal personalAmount = queryTransactionSum(agentId, type, 1);

        personal.setAmount(personalAmount);
        //合伙人
        int personalAgentCount = agentService.queryAgentAddCount(agentId, type, 1);
        personal.setAgentCount(personalAgentCount);
        List<TerMerchantReport> reports = merchantService.selectList(new EntityWrapper<TerMerchantReport>()
                .eq("agent_id", agentId)
                .eq("dept_id", agent.getDeptId())
        );
        Long count = reports.stream().count();
        int personalMerchantCount = count.intValue();
        personal.setMerchantCount(personalMerchantCount);
        map.put("personal", personal);
        //团队
        ExpandDto team = new ExpandDto();
        //交易
        BigDecimal teamAmount = queryTransactionSum(agentId, type, 3);
        team.setAmount(teamAmount);
        //合伙人6
        int teamAgentCount = agentService.queryAgentAddCount(agentId, type, 2);
        team.setAgentCount(teamAgentCount);
        //商户
        int teamMerchantCount = merchantService.queryMerchantCount(agentId, type, 3);
        team.setMerchantCount(teamMerchantCount);
        map.put("team", team);
        return map;
    }

    @Override
    public List<SeparatMonthView> queryTradeSeparationList(String token, Integer terminalType, Integer types, Integer pageNo) {
        if (types == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        Long depId = agent.getDeptId();
        List<SeparatMonthView> list = new ArrayList<>();
        if (pageNo != null) {
            List<TranBenefitDay> dayList = listDayList(agentId, pageNo * 10);

            List<Map<String, Object>> mapList = new LinkedList<>();

            for (TranBenefitDay d : dayList) {
                Map<String, Object> map = new HashedMap();

                String dayTimeStr = DateUtils.format(d.getBenefitDate(), DateUtils.DATE_PATTERN);

                map.put("dayTime", dayTimeStr); //天时间
                if (terminalType == null) { //全部终端类型查询
                    BigDecimal dayAmount = benefitDayService.getDayAmount(agentId, types, dayTimeStr);
                    map.put("dayAmount", dayAmount);//天收益
                    List<TranAmountView> daySpList = benefitInfoService.separatSelfDayList(terminalType, dayTimeStr, agentId, depId, types);
                    map.put("daySpList", daySpList);//终端明细收益
                } else {
                    //单个机具查询
                    if (terminalType == 5) { //乐刷数据
                        List<Map<String, Object>> leShuaDayList = benefitInfoService.queryLeShuaDayList(terminalType, dayTimeStr, agentId, depId, types);
                        map.put("leShuaDayList", leShuaDayList);
                    } else {
                        List<TranAmountView> daySpList = benefitInfoService.separatSelfDayList(terminalType, dayTimeStr, agentId, depId, types);
                        map.put("daySpList", daySpList);//终端明细收益
                    }
                }
                mapList.add(map);
            }
            if (mapList.size() > 0) {
                list = packToSeparatMonthView(agentId, types, mapList);
            }

        }

        return list;
    }

    @Override
    public List<TranBenefitDay> listDayList(Long agentId, String month) {
        return baseMapper.listDayList(agentId, month);
    }

    @Override
    public List<TranBenefitDay> listDayList(Long agentId, Integer start) {
        return baseMapper.listDayListByPage(agentId, start);
    }


    /**
     * 计算自营、团队交易分润同比和下个月数据
     * 公式：
     * 同比： (上个月 - 上上个月) / 上个月
     * 下个月预计： (上个月 - 上上个月) * (同比 / 2) + 上个月
     *
     * @param lastAmount
     * @param lastTwoAmount
     * @return
     */
    public static DividedSumDto nextEstimate(BigDecimal lastAmount, BigDecimal lastTwoAmount) {
        DividedSumDto d = new DividedSumDto();
        //除数为0的情况下
        if (lastAmount.compareTo(new BigDecimal("0")) == 0) {
            d.setLastAmount(lastAmount);
            d.setLastTwoAmount(lastTwoAmount);
            d.setNextAmount(new BigDecimal("0"));
            d.setWith(new BigDecimal("0"));
            return d;
        }
        //同比
        BigDecimal sub = lastAmount.subtract(lastTwoAmount);
        BigDecimal with = sub.divide(lastAmount, 2, ROUND_HALF_DOWN);
        //下个月预计
        BigDecimal s = with.divide(new BigDecimal(2));
        //下个月预估数据
        BigDecimal nextAmount = sub.multiply(s).add(lastAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
        d.setLastAmount(lastAmount);
        d.setLastTwoAmount(lastTwoAmount);
        d.setNextAmount(nextAmount);
        d.setWith(with);
        return d;
    }

    @Override
    public Map<String, Object> queryTransactionTimeMap(String token, Long agentId, String types, Integer pageNo) {
        if (pageNo == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        if (agentId == null || StringUtils.isBlank(types)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        if (!StringUtils.equals(types, "month") && !StringUtils.equals(types, "day")) {
            throw new RRException("9000", "types时间类型参数错误");
        }
        Map<String, Object> map = new HashedMap(2);
        List<TransactionListView> list;
        List<TransactionListView> actualList = new ArrayList<>();
        SysAgent agent = agentService.queryAgentByToken(token);
        //当前登录人的id
        Long agId = agent.getAgentId();
        //登录人的所属渠道
        Long depId = agent.getDeptId();
        //查询自己的交易
        Integer terType = 2;

        if (agentId.intValue() == agId.intValue()) {
            terType = 1;
        }
        //全部的交易
        if (agentId.intValue() == 0) {
            agentId = agId;
        }
        //admin查询全部的交易，解决数据量大的问题
        //平台查询交易
        SysAgent baseAgent = agentService.queryBasicAgentBydeptId(depId);


        if (agentId.equals(baseAgent.getAgentId()) && agId.equals(baseAgent.getAgentId()) && terType == 2) {
            terType = 3;
        }

        //本月的天数据
        if (StringUtils.equals(types, "day")) {
            //当月的第一天
            String tartDay = DateStrUtils.getPerFirstDayOfMonth();
            //系统昨天的时间
            String endDay = DateStrUtils.getDifferDate(0);
            list = DateStrUtils.getBetweenDates(tartDay, endDay);

            int totalNum = list.size();
            if (pageNo * 3 <= totalNum) {
                totalNum = pageNo * 3;
            }
            for (int i = (pageNo - 1) * 3; i < totalNum; i++) {
                String dayTime = list.get(i).getTime();
                //天总交易
                BigDecimal amount = baseMapper.getDayTranAmount(agentId, terType, dayTime, depId);
                List<TranAmountView> tranList = baseMapper.queryTranTimeList(agentId, dayTime, "day", depId, terType);
                //if (amount.compareTo(new BigDecimal("0.00")) == 1) {
                TransactionListView v = new TransactionListView();
                v.setAmount(amount);
                v.setTime(dayTime);
                v.setObjList(tranList);
                actualList.add(v);
                //}

            }
        } else {
            //获取最近一年时间
            list = StringUtil.getYearList();
            int totalNum = list.size();
            if (pageNo * 3 <= totalNum) {
                totalNum = pageNo * 3;
            }
            for (int i = (pageNo - 1) * 3; i < totalNum; i++) {
                String monthTime = list.get(i).getTime();
                //月总交易
                BigDecimal amount = baseMapper.getMonthTranAmount(agentId, terType, monthTime, depId);
                List<TranAmountView> tranList = baseMapper.queryTranTimeList(agentId, monthTime + "%", "month", depId, terType);
                //if (amount.compareTo(new BigDecimal("0.00")) == 1) {
                TransactionListView v = new TransactionListView();
                v.setAmount(amount);
                v.setTime(monthTime);
                v.setObjList(tranList);
                actualList.add(v);
                //}
            }
        }


        map.put("list", actualList);
        map.put("totalNum", list.size());
        return map;
    }


    @Override
    public BigDecimal queryLMonthTranSum(Long agentId) {
        return this.baseMapper.queryLMonthTranSum(agentId);
    }

    @Override
    public Integer insertTransaction(String fileName, MultipartFile file, Long deptId) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        //交易列表
        List<TranTransactionInfo> transactionInfos = new ArrayList<>();
        //交易对象临时变量
        TranTransactionInfo transactionInfo;
        //终端对象临时变量
        TerTerminalInfo terTerminalInfo;
        BigDecimal totalAmount = new BigDecimal("0.00");
        Integer count = 0;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            transactionInfo = new TranTransactionInfo();
            String merchantCode = row.getCell(0).getStringCellValue().trim();
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            BigDecimal money = new BigDecimal(row.getCell(1).getStringCellValue().trim());

            int terminalType = Integer.valueOf(row.getCell(2).getStringCellValue().trim());

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = dateFormat.parse(row.getCell(3).getStringCellValue().trim());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String isVipStr = row.getCell(4).getStringCellValue().trim();
            //其余需要根据商户查询出终端号
            System.out.println(merchantCode);
            terTerminalInfo = terminalInfoService.queryTerminalByMCode(merchantCode);
            //查不到则不添加
            if (terTerminalInfo == null) {
                continue;
            }
            totalAmount = totalAmount.add(money);
            transactionInfo.setSn(terTerminalInfo.getSn());

            //设置交易的属性
            transactionInfo.setAmount(money);
            transactionInfo.setTransactionDate(date);
            transactionInfo.setDeptId(deptId);
            transactionInfo.setTerminalType(terminalType);
            transactionInfo.setIsVip(isVipStr);
            transactionInfo.setCreateDate(new Date());
            transactionInfo.setMerchantCode(merchantCode);
            //加入列表
            transactionInfos.add(transactionInfo);
            count += this.baseMapper.insert(transactionInfo);
        }


        if (deptId.equals(1L)) {
            List<LogAccount> logAccounts = queryTerAccountList(transactionInfos.get(0).getTerminalType());
            if (logAccounts.size() > 0) {
                LogAccount logAccount = logAccounts.get(0);
                LogTranInfo logTranInfo = new LogTranInfo();
                logTranInfo.setAccountId(logAccount.getAccountId());
                logTranInfo.setLogStates("SUCCESS");
                logTranInfo.setExplainsInfo(logAccount.getExpInfo() + "-导入成功");
                logTranInfo.setCreateDate(new Date());
                logTranInfo.setTotalNumber(count);
                logTranInfo.setTotalTransaction(totalAmount);
                logTranInfoService.insert(logTranInfo);
            }
        }

        return count;
    }


    @Override
    public PageUtils queryTranList(Map<String, Object> params) {
        //时间为空时设置为null
        if ("".equals(params.get("startDate"))) {
            params.put("startDate", null);
        }
        if ("".equals(params.get("endDate"))) {
            params.put("endDate", null);
        }
        Integer pageSize = Integer.valueOf(params.get("limit").toString());
        Integer currPage = Integer.valueOf(params.get("page").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        //交易列表
        List<Map<String, Object>> list = baseMapper.queryTranList(params);
        //交易数量
        Integer totalCount = baseMapper.queryTranCount(params);
        //转换格式
        for (Map<String, Object> map : list) {
            map.put("amount", MathUtils.formatToNumber(new BigDecimal(map.get("amount").toString())));
        }
        return new PageUtils(list, totalCount, pageSize, currPage);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTransactionKaYou(String sessionId, Long accountId, String expInfo) {
        try {
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            //String date = "2017-11-22";
            //String dates = "2017-10-30";
            //根据session访问卡友网站
            String requestUrl2 = "https://vip.cardinfo.com.cn/agent/orderQuery.action?amountStart=&authorizationCode=&pagingPage=1&createTimeEnd=" + date + "&cardType=&externalId=&createTimeStart=" + date + "&radio=on&amountEnd=&customerType=iCust&sortColumn=id&sortColumn=id&sortDirection=-1&transType=&panEnd=&customerNo=&posCati=&status=SETTLED%2CSUCCESS&transWay=&secondAgentName=";
            String repost2 = HttpClean.httpsRequest(requestUrl2, "POST", null, sessionId);
            Document doc2 = Jsoup.parse(repost2);


            String pageDoc = doc2.getElementsByClass("search_resultsSummary").toString();
            String pageString = pageDoc.substring(pageDoc.indexOf("共<b>"), pageDoc.indexOf("</td>"));
            String d = pageString.substring(pageString.indexOf("共<b>") + 4, pageString.indexOf("</b>页 "));
            int page = Integer.valueOf(d);
            for (int k = 1; k <= page; k++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }//暂停1.5秒后程序继续执行
                Elements trs = HttpClean.getData(date, k, sessionId);
                //判断超时
                for (int i = 1; i < trs.size() - 2; i++) {
                    Elements tds = trs.get(i).select("td");
                    if (tds != null && tds.size() != 0) {
                        for (int j = 0; j < 1; j++) {
                            //找到查询的id
                            String idDoc = tds.get(9).toString();
                            //String idDoc = ss.getElementsByClass("search_results").toString();
                            String id = idDoc.substring(idDoc.indexOf("javascript:detail('") + 19, idDoc.indexOf("');"));
                            //交易状态
                            String sate = tds.get(6).text();
                            //交易金额
                            String amount = tds.get(5).text();
                            //交易商户号
                            String merchantCode = tds.get(2).text();
                            System.out.print("=================id为" + id);
                            System.out.print("=================商户号" + merchantCode);
                            if (StringUtils.equals("成功", sate) && StringUtils.isNotBlank(merchantCode) && StringUtils.isNotBlank(id)) {
                                //查询终端号是否存在，不存在在查询pos机器码去查询
                                TerTerminalInfo terminal = terminalInfoService.queryTerminalByMCode(merchantCode);
                                if (terminal == null) {
                                    //查询posSN号
                                    String sn = HttpClean.querKayouPosSn(id, sessionId);
                                    if (StringUtils.isNotBlank(sn)) {
                                        terminal = terminalInfoService.queryTerminalBySn(sn);
                                        //修改
                                        terminal.setMerchantCode(merchantCode);
                                        terminalInfoService.updateTerminal(terminal);
                                    }
                                }
                                if (terminal != null) {
                                    totalNumber++; //累计添加交易笔数
                                    totalTransaction = totalTransaction.add(new BigDecimal(amount));//累计添加交易总额
                                    //录入交易
                                    Integer terminalType = terminal.getTerminalType();//交易类型
                                    Long agentId = distribuService.queryTerminalOwn(terminal.getSn());//所属代理商
                                    System.out.print("代理商id===================" + agentId);
                                    SysAgent agent = agentService.queryAgentById(agentId);
                                    Long deptId = agent.getDeptId();//所属渠道
                                    TranTransactionInfo t = new TranTransactionInfo();
                                    t.setAmount(new BigDecimal(amount));
                                    t.setCreateDate(new Date());
                                    t.setDeptId(deptId);
                                    t.setIsVip("否");
                                    t.setTerminalType(terminalType);
                                    t.setMerchantCode(merchantCode);
                                    t.setSn(terminal.getSn());
                                    t.setTransactionDate(DateUtils.stringToDate(date, DateUtils.DATE_PATTERN));
                                    baseMapper.insert(t);
                                }
                            }
                        }
                    }
                }
            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo(expInfo + "-成功");
            log.setAccountId(accountId);
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            insertTerLog(log);
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }
    }

    @Override
    public void addTransactionKaiDianBao(String sessionId, Long accountId, String expInfo) {
        try {
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            //String date = "2017-11-22";
            //String dates = "2017-10-30";
            //根据session访问卡友网站
            String requestUrl2 = "https://v.91dbq.com/agent/orderQuery.action?createTimeStart=" + date + "&createTimeEnd=" + date + "&radio=on&posCati=&panEnd=&cardType=CREDIT_CARD&customerNo=&externalId=&status=SETTLED,SUCCESS&transType=PURCHASE&actTransStyle=&authorizationCode=&amountStart=&amountEnd=&secondAgentName=&customerType=bigCust";
            String repost2 = HttpClean.httpsRequest(requestUrl2, "POST", null, sessionId);
            Document doc2 = Jsoup.parse(repost2);
            String pageDoc = doc2.getElementsByClass("search_resultsSummary").toString();
            String pageString = pageDoc.substring(pageDoc.indexOf("共<b>"), pageDoc.indexOf("</td>"));
            String d = pageString.substring(pageString.indexOf("共<b>") + 4, pageString.indexOf("</b>页 "));
            int page = Integer.valueOf(d);
            for (int k = 1; k <= page; k++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }//暂停1.5秒后程序继续执行
                Elements trs = HttpClean.getKaiDianBaoData(date, k, sessionId);
                //判断超时
                for (int i = 1; i < trs.size() - 2; i++) {
                    Elements tds = trs.get(i).select("td");
                    if (tds != null && tds.size() != 0) {
                        for (int j = 0; j < 1; j++) {
                            //找到查询的id
                            String idDoc = tds.get(9).toString();
                            //String idDoc = ss.getElementsByClass("search_results").toString();
                            String id = idDoc.substring(idDoc.indexOf("javascript:detail('") + 19, idDoc.indexOf("');"));
                            //交易状态
                            String sate = tds.get(6).text();
                            //交易金额
                            String amount = tds.get(5).text();
                            //交易商户号
                            String merchantCode = tds.get(2).text();
                            System.out.print("=================id为" + id);
                            System.out.print("=================商户号" + merchantCode);
                            if (StringUtils.equals("成功", sate) && StringUtils.isNotBlank(merchantCode) && StringUtils.isNotBlank(id)) {
                                //查询终端号是否存在，不存在在查询pos机器码去查询
                                TerTerminalInfo terminal = terminalInfoService.queryTerminalByMCode(merchantCode);
                                if (terminal == null) {
                                    //查询posSN号
                                    String sn = HttpClean.querKaiDianBaoPosSn(id, sessionId);
                                    if (StringUtils.isNotBlank(sn)) {
                                        terminal = terminalInfoService.queryTerminalBySn(sn);
                                        //修改
                                        terminal.setMerchantCode(merchantCode);
                                        if (terminal != null) {
                                            terminalInfoService.updateTerminal(terminal);
                                        }
                                    }
                                }
                                if (terminal != null) {
                                    totalNumber++; //累计添加交易笔数
                                    totalTransaction = totalTransaction.add(new BigDecimal(amount));//累计添加交易总额
                                    //录入交易
                                    Integer terminalType = terminal.getTerminalType();//交易类型
                                    Long agentId = distribuService.queryTerminalOwn(terminal.getSn());//所属代理商
                                    System.out.print("代理商id===================" + agentId);
                                    SysAgent agent = agentService.queryAgentById(agentId);
                                    Long deptId = agent.getDeptId();//所属渠道
                                    TranTransactionInfo t = new TranTransactionInfo();
                                    t.setAmount(new BigDecimal(amount));
                                    t.setCreateDate(new Date());
                                    t.setDeptId(deptId);
                                    t.setIsVip("否");
                                    t.setTerminalType(terminalType);
                                    t.setMerchantCode(merchantCode);
                                    t.setSn(terminal.getSn());
                                    t.setTransactionDate(DateUtils.stringToDate(date, DateUtils.DATE_PATTERN));
                                    baseMapper.insertTransaction(t);
                                }
                            }
                        }
                    }
                }
            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo(expInfo + "-成功");
            log.setAccountId(accountId);
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            insertTerLog(log);
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }
    }

    @Override
    public void addTransactionLeShua(String sessionId, Long accountId, String expInfo) {
        try {
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            Integer t0Flag = 0; //0：(T+1)  1:(T+0)
            String t0FlagName = "T+1";
            //查询交易列表 需要2次查询 还有一次T+1 的68交易
            for (int s = 0; s < 2; s++) {
                Integer totalNumber = 0;
                BigDecimal totalTransaction = new BigDecimal("0.00");
                if (s == 1) {
                    t0Flag = 1;
                    t0FlagName = "T+0";
                }
                List<LeShuaTranView> list = HttpClean.getLeShuaTranList(sessionId, date, t0Flag);
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        String merchantNo = list.get(i).getMerchantId(); //商户号
                        String sn = list.get(i).getPinpadUuid();//SN号码
                        BigDecimal amount = list.get(i).getAmount().divide(new BigDecimal("100"));//交易金额
                        Integer isVip = list.get(i).getVipFlag();//是否VIP商户 0:否 1：是
                        //T+1 的只导入68的
                        if (t0Flag == 0 && amount.compareTo(new BigDecimal("68")) == 0 || t0Flag == 1) {
                            //根据商户号查询是否存在
                            TerTerminalInfo t = terminalInfoService.queryTerminalByMCode(merchantNo);
                            TerTerminalInfo t1 = terminalInfoService.queryTerminalBySn(sn);
                            if (t == null && t1 != null) {
                                t1.setMerchantCode(merchantNo);
                                terminalInfoService.updateTerminal(t1);
                            }
                            //录入交易
                            if (t1 != null) {
                                totalNumber++; //累计添加交易笔数
                                totalTransaction = totalTransaction.add(amount);//累计添加交易总额
                                //录入交易
                                Integer terminalType = t1.getTerminalType();//交易类型
                                Long agentId = distribuService.queryTerminalOwn(sn);//所属代理商
                                System.out.print("代理商id===================" + agentId);
                                SysAgent agent = agentService.queryAgentById(agentId);
                                Long deptId = agent.getDeptId();//所属渠道
                                TranTransactionInfo tranTransactionInfo = new TranTransactionInfo();
                                tranTransactionInfo.setAmount(amount);
                                tranTransactionInfo.setCreateDate(new Date());
                                tranTransactionInfo.setDeptId(deptId);
                                if (isVip == 0) {
                                    tranTransactionInfo.setIsVip("否");
                                } else {
                                    tranTransactionInfo.setIsVip("是");
                                }
                                tranTransactionInfo.setTerminalType(terminalType);
                                tranTransactionInfo.setMerchantCode(merchantNo);
                                tranTransactionInfo.setSn(sn);
                                tranTransactionInfo.setTransactionDate(DateUtils.stringToDate(date, DateUtils.DATE_PATTERN));
                                tranTransactionInfo.setTransactionType(t0FlagName);
                                baseMapper.insertTransaction(tranTransactionInfo);
                            }
                        }
                    }
                    //录入交易导入日志
                    LogTranInfo log = new LogTranInfo();
                    log.setExplainsInfo(expInfo + "-" + t0FlagName + "-成功");
                    log.setAccountId(accountId);
                    log.setLogStates("SUCCESS");
                    log.setTotalNumber(totalNumber);
                    log.setTotalTransaction(totalTransaction);
                    insertTerLog(log);
                } else {
                    insertFailTerLog(expInfo + "-" + t0FlagName + "-未查询到交易信息", accountId);
                }
            }
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }
    }

    @Override
    public void addTransactionLeShuaBig(String sessionId, Long accountId, String expInfo) {

        try {
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            System.out.print("乐刷大POS时间==============" + date);
            //查询交易列表
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            List<LeShuaTranBigView> list = HttpClean.getLeShuaBigList(sessionId, date);
            System.out.println("乐刷大POS数据数量==============" + list.size());
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    String merchantNo = list.get(i).getPosCati(); //商户号
                    String transactionDate = DateStrUtils.transferLongToDate(DateStrUtils.Y_M_D, list.get(i).getCreateTime()); //交易时间
                    BigDecimal amount = new BigDecimal(list.get(i).getAmount()).divide(new BigDecimal("100"));//交易金额
                    //根据商户号查询是否存在，不存在进行修改商户号操作
                    TerTerminalInfo t = terminalInfoService.queryTerminalByMCode(merchantNo);
                    if (t == null) {
                        String sn = HttpClean.queryLeShuaBigMerchantNo(sessionId, merchantNo);
                        TerTerminalInfo t1 = terminalInfoService.queryTerminalBySn(sn);
                        t1.setMerchantCode(merchantNo);
                        terminalInfoService.updateTerminal(t1);
                        t = terminalInfoService.queryTerminalByMCode(merchantNo);
                    }
                    if (t != null) {
                        //录入交易
                        totalNumber++; //累计添加交易笔数
                        totalTransaction = totalTransaction.add(amount);//累计添加交易总额
                        //录入交易
                        Integer terminalType = t.getTerminalType();//交易类型
                        Long agentId = distribuService.queryTerminalOwn(t.getSn());//所属代理商
                        SysAgent agent = agentService.queryAgentById(agentId);
                        Long deptId = agent.getDeptId();//所属渠道
                        TranTransactionInfo tranTransactionInfo = new TranTransactionInfo();
                        tranTransactionInfo.setAmount(amount);
                        tranTransactionInfo.setCreateDate(new Date());
                        tranTransactionInfo.setDeptId(deptId);
                        tranTransactionInfo.setIsVip("否");
                        tranTransactionInfo.setTerminalType(terminalType);
                        tranTransactionInfo.setMerchantCode(merchantNo);
                        tranTransactionInfo.setSn(t.getSn());
                        tranTransactionInfo.setTransactionDate(DateUtils.stringToDate(transactionDate, DateUtils.DATE_PATTERN));
                        baseMapper.insertTransaction(tranTransactionInfo);
                    }
                }
            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo(expInfo + "-" + "-成功");
            log.setAccountId(accountId);
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            insertTerLog(log);
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }

    }

    @Override
    public void addTransactionRuiHeBao(String sessionId, Long accountId, String expInfo) {


        try {
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            //String date="2019-10-03";
            //去除时间的-符号
            String dateStr = date.replace("-", "");
            //查询交易列表
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            List<RuiHeBaoView> list = HttpClean.getRuiHeBaoList(sessionId, dateStr);
            if (list != null) {
                for (RuiHeBaoView v : list) {
                    String merchantNo = v.getTerminalId(); //商户号,比终端号多最后一位
                    BigDecimal amount = v.getTransacount();//交易金额
                    //根据商户号查询是否存在
                    TerTerminalInfo t = terminalInfoService.queryTerminalByMCode(merchantNo);
                    if (t != null) {
                        //录入交易
                        totalNumber++; //累计添加交易笔数
                        totalTransaction = totalTransaction.add(amount);//累计添加交易总额
                        //录入交易
                        Integer terminalType = t.getTerminalType();//交易类型
                        Long agentId = distribuService.queryTerminalOwn(t.getSn());//所属代理商
                        SysAgent agent = agentService.queryAgentById(agentId);
                        Long deptId = agent.getDeptId();//所属渠道
                        TranTransactionInfo tranTransactionInfo = new TranTransactionInfo();
                        tranTransactionInfo.setAmount(amount);
                        tranTransactionInfo.setCreateDate(new Date());
                        tranTransactionInfo.setDeptId(deptId);
                        tranTransactionInfo.setIsVip("否");
                        tranTransactionInfo.setTerminalType(terminalType);
                        tranTransactionInfo.setMerchantCode(merchantNo);
                        tranTransactionInfo.setSn(t.getSn());
                        tranTransactionInfo.setTransactionDate(DateUtils.stringToDate(date, DateUtils.DATE_PATTERN));
                        baseMapper.insertTransaction(tranTransactionInfo);
                    }
                }
            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo(expInfo + "-" + "-成功");
            log.setAccountId(accountId);
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            insertTerLog(log);
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }


    }

    @Override
    public Map<String, Object> queryPersonAmountDetail(Map<String, Object> params) {
        if ("".equals(params.get("startDate"))) {
            params.put("startDate", null);
        }
        if ("".equals(params.get("endDate"))) {
            params.put("endDate", null);
        }
        Map<String, Object> resultMap = new HashMap<>(3);
        BigDecimal totalAmount = this.baseMapper.queryPersonTotalAmount(params);
        BigDecimal ownerAmount = this.baseMapper.queryPersonOwnerAmount(params);
        BigDecimal teamAmount = this.baseMapper.queryPersonTeamAmount(params);
        resultMap.put("totalAmount", totalAmount);
        resultMap.put("ownerAmount", ownerAmount);
        resultMap.put("teamAmount", teamAmount);
        return resultMap;
    }

    @Override
    public PageUtils queryPersonTradeDetail(Map<String, Object> params) {
        if ("".equals(params.get("startDate"))) {
            params.put("startDate", null);
        }
        if ("".equals(params.get("endDate"))) {
            params.put("endDate", null);
        }

        Integer pageSize = Integer.valueOf(params.get("limit").toString());
        Integer currPage = Integer.valueOf(params.get("page").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> list = baseMapper.queryPersonTradeDetail(params);
        Integer totalCount = baseMapper.queryPersonTradeCount(params);
        return new PageUtils(list, totalCount, pageSize, currPage);
    }


    @Override
    public List<LogAccount> queryTerAccountList(Integer terminalType) {
        return baseMapper.queryTerAccountList(terminalType);
    }

    @Override
    public void insertTerLog(LogTranInfo log) {
        log.setCreateDate(new Date());
        baseMapper.insertTerLog(log);
    }

    @Override
    public void insertFailTerLog(String explainsInfo, Long accountId) {
        LogTranInfo log = new LogTranInfo();
        log.setAccountId(accountId);
        log.setLogStates("FAIL");
        log.setTotalNumber(0);
        log.setTotalTransaction(new BigDecimal("0.00"));
        log.setExplainsInfo(explainsInfo);
        insertTerLog(log);
    }

    @Override
    public void addLeShuaVip(String sessionId, Long accountId, String expInfo) {
        try {
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            List<LeShuaVipView> list = HttpClean.getLeShuaVipList(sessionId, date);
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    String merchantNo = list.get(i).getMerchantId(); //商户号
                    String dateStr = list.get(0).getEffectiveStartTime();
                    String[] splited = dateStr.split("\\s+");
                    String effectiveStartTime = splited[0];
                    //根据商户号查询是否存在
                    TerTerminalInfo t = terminalInfoService.queryTerminalByMCode(merchantNo);
                    //录入流水和VIP返现数据
                    if (t != null) {
                        String sn = t.getSn();
                        Long agentId = distribuService.queryTerminalOwn(sn);//所属代理商
                        BigDecimal amount = new BigDecimal("150");
                        //查询是否已经录入我们数据库
                        Integer isVipCount = baseMapper.queryVipBackByNo(merchantNo, effectiveStartTime);
                        if (isVipCount == 0) {
                            totalNumber++; //累计添加交易笔数
                            totalTransaction = totalTransaction.add(amount);//累计添加交易总额
                            //录入VIP返现记录
                            Long id = baseMapper.getVipMax() + 1;
                            baseMapper.insertVipBack(id, merchantNo, sn, amount, agentId, effectiveStartTime);
                            //录入流水日志
                            FlowAccount account = new FlowAccount();
                            account.setBelId(String.valueOf(id));
                            account.setAmount(amount);
                            account.setAccountType(8);
                            account.setAgentId(agentId);
                            account.setSupportType(2);
                            flowAccountService.insertFlowAccount(account);
                            //修改账户余额
                            agentInfoService.addAmount(agentId, amount);
                        }
                    }
                }
            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo(expInfo + "-成功");
            log.setAccountId(accountId);
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            insertTerLog(log);
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }
    }

    @Override
    public String querytotalAmount(Map<String, Object> params) {
        if ("".equals(params.get("startDate"))) {
            params.put("startDate", null);
        }
        if ("".equals(params.get("endDate"))) {
            params.put("endDate", null);
        }
        //查询交易额列表
        List<BigDecimal> amountList = baseMapper.queryAmountList(params);

        BigDecimal totalAmount = amountList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        return MathUtils.formatToNumber(totalAmount);
    }

    @Override
    public List<Map<String, Object>> queryListBySn(String sn, String startDate, String endDate) {
        return baseMapper.queryListBySn(sn, startDate, endDate);
    }

    @Override
    public Map<String, Object> queryTranListBySn(String sn, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>(2);
        List<Map<String, Object>> list = queryListBySn(sn, startDate, endDate);

        BigDecimal totalAmount = list.stream().map(e -> new BigDecimal(e.get("amount").toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
        result.put("list", list);
        result.put("totalAmount", totalAmount);
        return result;
    }

    @Override
    public String addTransactionByLeShuaBig(String data, String sign) {
        if (data == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        if (sign == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }


        String result = "";
        Gson gson = new Gson();
        BigLeShuaTransactionInfo leshuatran = gson.fromJson(data, BigLeShuaTransactionInfo.class);
        if (leshuatran == null) {
            throw new RRException("9000", "转换失败");
        }
        TransactionInput ti = transactionInputService.selectById(leshuatran.getOrderId());
        if (ti != null) {
            return "000000";
        }

        if (leshuatran.getStatus().intValue() == 5) {
            String mCode = leshuatran.getPosCati();
            System.out.println(mCode);
            TerTerminalInfo t = terminalInfoService.queryTerminalByMCode(mCode);

            if (t == null) {
                result = "000000";
                return result;
            }
            String str = leshuatran.getTradeDate().substring(0, leshuatran.getTradeDate().indexOf(" "));
            if (leshuatran.getOrderId() == null || "".equals(leshuatran.getOrderId())) {
                result = "000000";
                return result;
            }
            TranTransactionInfo info = new TranTransactionInfo();
            info.setIsVip("否");
            BigDecimal amount = leshuatran.getAmount().divide(new BigDecimal("100"));
            info.setAmount(amount);
            info.setCreateDate(new Date());
            info.setDeptId(t.getDeptId());
            info.setMerchantCode(t.getMerchantCode());
            info.setSn(t.getSn());
            info.setTerminalType(t.getTerminalType());
            info.setTransactionDate(DateUtils.stringToDate(str, DateUtils.DATE_PATTERN));
            baseMapper.insertTransaction(info);
            TransactionInput tranIn = new TransactionInput();
            tranIn.setOrderId(leshuatran.getOrderId());
            tranIn.setCreateDate(new Date());
            transactionInputService.insert(tranIn);
            result = "000000";
        }
        return result;
    }


    /**
     * 获取商户详情列表
     *
     * @param
     * @return
     */
    public List<SeparatMonthView> packToSeparatMonthView(Long agentId, Integer types, List<Map<String, Object>> mapList) {

        List<SeparatMonthView> smvList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        //获取列表第一天的月份
        int count = 0;
        while (true) {

            if (count == mapList.size()) {
                break;
            }
            String dayTime = mapList.get(count).get("dayTime").toString();
            String time = sdf.format(DateUtils.stringToDate(dayTime, DateUtils.DATE_PATTERN));
            SeparatMonthView smv = new SeparatMonthView();
            smv.setTime(time);
            BigDecimal monthAmount = benefitDayService.getMonthAmount(agentId, types, time);
            smv.setAmount(monthAmount);
            List<Map<String, Object>> temp = new ArrayList<>();
            String timeTemp;
            for (int i = count; i < mapList.size(); i++) {
                dayTime = mapList.get(count).get("dayTime").toString();
                timeTemp = sdf.format(DateUtils.stringToDate(dayTime, DateUtils.DATE_PATTERN));
                if (time.equals(timeTemp)) {
                    temp.add(mapList.get(count));
                    count++;
                }
            }
            smv.setObjList(temp);
            smvList.add(smv);
        }
        return smvList;
    }

    @Override
    public List<TranTransactionInfo> queryYesterdayListBySn(String sn, String benefitDateStr, Long deptId) {
        return baseMapper.queryYesterdayListBySn(sn, benefitDateStr, deptId);
    }

    @Override
    public List<TranTransactionInfo> queryListBySnAndTime(String sn, Date endDate) {
        return baseMapper.queryListBySnAndTime(sn, endDate);
    }

    @Override
    public Map<String, Object> getStarPosTransaction(String sdTermNo, String txnDate, String txnAmt, String txnStatus, String txnLogId) {
        Map<String, Object> result = new HashMap<>(2);

        if (!"1".equals(txnStatus)) {
            result.put("RspCode ", "000000");
            result.put("RspDes", "非成功交易");
            return result;
        }
        StarposTranInput input = starposTranInputService.selectById(txnLogId);
        if (input != null) {
            result.put("RspCode ", "000000");
            result.put("RspDes", "交易已导入");
            return result;
        }
        TerTerminalInfo t = terminalInfoService.queryTerminalByMCode(sdTermNo);
        if (t == null) {
            result.put("RspCode ", "000000");
            result.put("RspDes", "无此终端");
            return result;
        }

        Date date = DateUtils.stringToDate(txnDate, "yyyyMMdd");
        TranTransactionInfo info = new TranTransactionInfo();
        info.setIsVip("否");
        BigDecimal amount = new BigDecimal(txnAmt);
        info.setAmount(amount);
        info.setCreateDate(new Date());
        info.setDeptId(t.getDeptId());
        info.setMerchantCode(t.getMerchantCode());
        info.setSn(t.getSn());
        info.setTerminalType(t.getTerminalType());
        info.setTransactionDate(date);
        baseMapper.insertTransaction(info);
        StarposTranInput i = new StarposTranInput();
        i.setCreateDate(new Date());
        i.setTxnLogId(txnLogId);
        starposTranInputService.insert(i);
        result.put("RspCode ", "000000");
        result.put("RspDes", "导入成功");
        return result;
    }


    @Override
    public String addTransactionByLeShuaBigSn(String data, String sign) {
        if (data == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        if (sign == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }


        String result = "";
        Gson gson = new Gson();
        BigLeShuaTransactionInfoSn leshuatran = gson.fromJson(data, BigLeShuaTransactionInfoSn.class);
        if (leshuatran == null) {
            throw new RRException("9000", "转换失败");
        }
        TransactionInput ti = transactionInputService.selectById(leshuatran.getOrderId());
        if (ti != null) {
            return "000000";
        }

        if (leshuatran.getStatus().intValue() == 5) {
            String sn = leshuatran.getSn();
            System.out.println(sn);
            System.out.println(leshuatran.getPosCati());
            TerTerminalInfo t = terminalInfoService.queryTerminalBySn(sn);
            if (t == null) {
                result = "000000";
                return result;
            }
            String str = leshuatran.getTradeDate().substring(0, leshuatran.getTradeDate().indexOf(" "));
            if (leshuatran.getOrderId() == null || "".equals(leshuatran.getOrderId())) {
                result = "000000";
                return result;
            }

            TranTransactionInfo info = new TranTransactionInfo();
            info.setIsVip("否");
            BigDecimal amount = leshuatran.getAmount().divide(new BigDecimal("100"));
            info.setAmount(amount);
            info.setCreateDate(new Date());
            info.setDeptId(t.getDeptId());
            info.setMerchantCode(leshuatran.getPosCati());
            info.setSn(t.getSn());
            info.setTerminalType(t.getTerminalType());
            info.setTransactionDate(DateUtils.stringToDate(str, DateUtils.DATE_PATTERN));
            baseMapper.insertTransaction(info);
            TransactionInput tranIn = new TransactionInput();
            tranIn.setOrderId(leshuatran.getOrderId());
            tranIn.setCreateDate(new Date());
            transactionInputService.insert(tranIn);
            result = "000000";
        }
        return result;
    }

    @Override
    public Map<String, Object> querySumTranBySn(String sn, Date startDate) {
        return baseMapper.querySumTranBySn(sn, startDate);
    }

    @Override
    public Integer insertKaoLatran(String fileName, MultipartFile file, Long deptId) {

        Integer count = 0;

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }


        TranTransactionInfo transactionInfo; //交易对象临时变量
        TerTerminalInfo terTerminalInfo;    //终端对象临时变量
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            transactionInfo = new TranTransactionInfo();
            String merchantCode = row.getCell(0).getStringCellValue().trim();
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            BigDecimal money = new BigDecimal(row.getCell(1).getStringCellValue().trim());

            int terminalType = Integer.valueOf(row.getCell(2).getStringCellValue().trim());

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = dateFormat.parse(row.getCell(3).getStringCellValue().trim());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String isVipstr = row.getCell(4).getStringCellValue().trim();
            //其余需要根据商户查询出终端号
            System.out.println(merchantCode);
            terTerminalInfo = terminalInfoService.queryTerminalByMCode(merchantCode);
            //查不到则不添加
            if (terTerminalInfo == null) {
                System.out.println("---未添加" + merchantCode);
                continue;
            }
            String isSpecial = row.getCell(5).getStringCellValue().trim();
            Integer isSpecialnum;
            if (StringUtil.isEmpty(isSpecial)) {
                isSpecialnum = 1;
            } else {
                isSpecialnum = Integer.valueOf(isSpecial);
            }
            transactionInfo.setSn(terTerminalInfo.getSn());

            //设置交易的属性
            transactionInfo.setAmount(money);
            transactionInfo.setTransactionDate(date);
            transactionInfo.setDeptId(deptId);
            transactionInfo.setTerminalType(terminalType);
            transactionInfo.setIsVip(isVipstr);
            transactionInfo.setCreateDate(new Date());
            transactionInfo.setMerchantCode(merchantCode);
            transactionInfo.setKaolaType(isSpecialnum);

            Integer num = baseMapper.insert(transactionInfo);
            count += num;

        }

        return count;
    }

    @Override
    public Map<String, String> getLishuaYajin(LiShuaYajin liShuaYajin) {

        Map<String, String> result = new HashMap<>();

        System.out.println("立刷押金时间:" + liShuaYajin.getTransTime());
        System.out.println("立刷订单号:" + liShuaYajin.getOrderId());
        System.out.println("立刷Sn:" + liShuaYajin.getPossn());
        if (liShuaYajin.getOrderId() == null || "".equals(liShuaYajin.getOrderId())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "orderId不能为空");
            return result;
        }

        TransactionInputLishua tinput = transactionInputLishuaService.selectById(liShuaYajin.getOrderId());
        if (tinput != null) {
            result.put("ret_code", "00");
            result.put("ret_msg", "success");
            return result;
        }

        if (liShuaYajin.getPossn() == null || "".equals(liShuaYajin.getPossn())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "possn不能为空");
            return result;
        }
        TerTerminalInfo t = terminalInfoService.queryTerminalBySn(liShuaYajin.getPossn());
        if (liShuaYajin.getAmount() == null || "".equals(liShuaYajin.getAmount())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "交易金额不能为空");
            return result;
        }
        if (liShuaYajin.getTransTime() == null || "".equals(liShuaYajin.getTransTime())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "交易时间不能为空");
            return result;
        }
        if (t != null) {
            TranTransactionInfo info = new TranTransactionInfo();

            Date date = DateUtils.stringToDate(liShuaYajin.getTransTime(), DateUtils.DATE_TIME_PATTERN);

            String dateStr = DateUtils.format(date, DateUtils.DATE_PATTERN);
            System.out.println(dateStr);
            info.setKaolaType(2);
            info.setIsVip("否");
            info.setMerchantCode(liShuaYajin.getPossn());
            info.setCreateDate(new Date());
            info.setDeptId(t.getDeptId());
            info.setAmount(new BigDecimal(liShuaYajin.getAmount()).divide(new BigDecimal("100")));
            info.setIsBenefited(0);
            info.setTransactionDate(DateUtils.stringToDate(dateStr, DateUtils.DATE_PATTERN));
            info.setTerminalType(t.getTerminalType());
            info.setSn(liShuaYajin.getPossn());
            baseMapper.insert(info);
            TransactionInputLishua lishua = new TransactionInputLishua();
            lishua.setCreateDate(new Date());
            lishua.setOrderId(liShuaYajin.getOrderId());
            transactionInputLishuaService.insert(lishua);

        }

        result.put("ret_code", "00");
        result.put("ret_msg", "success");
        return result;
    }

    @Override
    public Map<String, String> getLishuaTran(LishuaTran lishuaTran) {


        Map<String, String> result = new HashMap<>();

        if (lishuaTran.getOrder_id() == null || "".equals(lishuaTran.getOrder_id())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "orderId不能为空");
            return result;
        }


        TransactionInputLishua tinput = transactionInputLishuaService.selectById(lishuaTran.getOrder_id());
        if (tinput != null) {
            result.put("ret_code", "00");
            result.put("ret_msg", "success");
            return result;
        }
        if (lishuaTran.getPos_sn() == null || "".equals(lishuaTran.getPos_sn())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "possn不能为空");
            return result;
        }
        TerTerminalInfo t = terminalInfoService.queryTerminalBySn(lishuaTran.getPos_sn());
        if (lishuaTran.getAmount() == null || "".equals(lishuaTran.getAmount())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "交易金额不能为空");
            return result;
        }
        if (lishuaTran.getTrans_time() == null || "".equals(lishuaTran.getTrans_time())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "交易时间不能为空");
            return result;
        }
        String dateStr = lishuaTran.getTrans_time().substring(0, 4) + "-" + lishuaTran.getTrans_time().substring(4, 6) + "-" + lishuaTran.getTrans_time().substring(6, 8);
        if (lishuaTran.getRet_code() == null || "".equals(lishuaTran.getRet_code())) {
            result.put("ret_code", "99");
            result.put("ret_msg", "交易结果不能为空");
            return result;
        }
        System.out.println("sn:" + lishuaTran.getPos_sn());
        System.out.println("交易时间:" + lishuaTran.getTrans_time());
        System.out.println("交易类型:" + lishuaTran.getBusi_sub_type());
        System.out.println("支付类型:" + lishuaTran.getPay_type());


        //交易成功
        if ("00".equals(lishuaTran.getRet_code())) {
            if (lishuaTran.getBusi_sub_type().contains("104")) {
                if (t != null) {
                    TranTransactionInfo info = new TranTransactionInfo();
                    Integer rateType = getRateType(lishuaTran.getPos_sn(), t.getDeptId());
                    info.setKaolaType(rateType);

                    info.setIsVip("否");
                    info.setMerchantCode(lishuaTran.getPos_sn());
                    info.setCreateDate(new Date());
                    info.setDeptId(t.getDeptId());
                    info.setAmount(new BigDecimal(lishuaTran.getAmount()).divide(new BigDecimal("100")));
                    info.setIsBenefited(0);
                    info.setTransactionDate(DateUtils.stringToDate(dateStr, DateUtils.DATE_PATTERN));
                    info.setTerminalType(t.getTerminalType());
                    info.setSn(lishuaTran.getPos_sn());
                    baseMapper.insert(info);
                    TransactionInputLishua lishua = new TransactionInputLishua();
                    lishua.setCreateDate(new Date());
                    lishua.setOrderId(lishuaTran.getOrder_id());
                    transactionInputLishuaService.insert(lishua);
                }
            }


        }
        result.put("ret_code", "00");
        result.put("ret_msg", "success");
        return result;
    }

    private Integer getRateType(String sn, Long deptId) {
        List<TranTransactionInfo> list = baseMapper.selectPage(new RowBounds(0, 1), new EntityWrapper<TranTransactionInfo>().eq("sn", sn).eq("dept_id", deptId).orderBy("transaction_date", true));
        if (list.size() != 1) {
            return 2;
        } else {
            Date beginDate = list.get(0).getTransactionDate();

            Date curDate = DateUtils.addDateMonths(beginDate, 3);

            if (new Date().compareTo(curDate) != 1) {
                return 2;
            } else {
                TerLishuaVip lishuaVip = terLishuaVipService.queryBySn(sn);

                if (lishuaVip == null) {
                    return 1;
                } else {
                    Date date = new Date();

                    if (date.compareTo(lishuaVip.getStartDate()) == 1 && date.compareTo(lishuaVip.getEndDate()) == -1) {
                        return 2;
                    } else {
                        return 1;
                    }

                }
            }


        }


    }


    @Override
    public Map<String, Object> deleteTranByIds(Long[] ids) {
        List<Long> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        for (Long str : ids) {
            TranTransactionInfo info = selectById(str);
            if (info.getIsBenefited().intValue() == 1) {
                list.add(str);
            } else {
                deleteById(str);
            }
        }
        if (list.size() > 0) {
            map.put("code", 999);
            map.put("msg", "部分失败");
            map.put("list", list);
        }

        return map;
    }

    @Override
    public Integer insertTLTransaction(String fileName, MultipartFile file, Long deptId) {
        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        TranTransactionInfo transactionInfo; //交易对象临时变量
        TerTerminalInfo terTerminalInfo;    //终端对象临时变量
        BigDecimal totalAmount = new BigDecimal("0.00");
        Integer count = 0;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            transactionInfo = new TranTransactionInfo();
            String merchantCode = row.getCell(0).getStringCellValue().trim();
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            BigDecimal money = new BigDecimal(row.getCell(1).getStringCellValue().trim());

            int terminalType = Integer.valueOf(row.getCell(2).getStringCellValue().trim());

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = dateFormat.parse(row.getCell(3).getStringCellValue().trim());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String rateStr = row.getCell(4).getStringCellValue().trim();

            BigDecimal rate = new BigDecimal(rateStr);

            rate = rate.subtract(new BigDecimal("3.00"));

            rate = rate.multiply(new BigDecimal("100")).divide(money, 2, 4);
            System.out.println(rate);
            Integer rateType;
            switch (rate.toString()) {
                case "0.50":
                    rateType = 1;
                    break;
                case "0.52":
                    rateType = 2;
                    break;
                case "0.55":
                    rateType = 3;
                    break;
                case "0.60":
                    rateType = 4;
                    break;
                default:
                    continue;
            }

            //其余需要根据商户查询出终端号

            terTerminalInfo = terminalInfoService.queryTerminalByMCode(merchantCode);
            //查不到则不添加
            if (terTerminalInfo == null) {
                continue;
            }
            totalAmount = totalAmount.add(money);
            transactionInfo.setSn(terTerminalInfo.getSn());

            //设置交易的属性
            transactionInfo.setAmount(money);
            transactionInfo.setTransactionDate(date);
            transactionInfo.setDeptId(deptId);
            transactionInfo.setTerminalType(terminalType);
            transactionInfo.setIsVip("否");
            transactionInfo.setCreateDate(new Date());
            transactionInfo.setMerchantCode(merchantCode);
            transactionInfo.setKaolaType(rateType);
            //加入列表
            count += baseMapper.insert(transactionInfo);
        }

        return count;
    }

    @Override
    public Map<String, Object> getExpandInfo(String token, Integer type) {
        Assert.isBlank(token, "token不能为空");
        Map<String, Object> map = new HashMap<>();
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //自营
        ExpandBean personal = new ExpandBean();
        if (type == null) {
            type = 2;
        }
        //交易
        BigDecimal personalAmount = queryTransactionSum(agentId, type, 1);
        personal.setAmount(MathUtils.formatToMoney(MathUtils.formatToNumber(personalAmount)));
        //合伙人
        int personalAgentCount = agentService.queryAgentAddCount(agentId, type, 1);
        personal.setAgentCount(personalAgentCount);
        List<TerMerchantReport> reports = merchantService.selectList(new EntityWrapper<TerMerchantReport>()
                .eq("agent_id", agentId)
                .eq("dept_id", agent.getDeptId())
        );
        Long count = reports.stream().count();
        int personalMerchantCount = count.intValue();
        personal.setMerchantCount(personalMerchantCount);
        map.put("personal", personal);
        //团队
        ExpandBean team = new ExpandBean();
        //交易
        BigDecimal teamAmount = queryTransactionSum(agentId, type, 3);
        //格式化后存储
        team.setAmount(MathUtils.formatToMoney(MathUtils.formatToNumber(teamAmount)));
        //合伙人6
        int teamAgentCount = agentService.queryAgentAddCount(agentId, type, 2);
        team.setAgentCount(teamAgentCount);
        //商户
        int teamMerchantCount = merchantService.queryMerchantCount(agentId, type, 3);
        team.setMerchantCount(teamMerchantCount);
        map.put("team", team);
        return map;
    }

    @Override
    public Map<String, Object> getIndexTran(String token, Integer type) {
        if (StringUtils.isBlank(token) || type == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        //type参数： 1-昨天 2-本月
        Map<String, Object> map = new HashMap<>(5);
        //查询缓存中所属人信息
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //团队交易
        BigDecimal teamAmount = queryTransactionSum(agentId, type, 2);

        map.put("teamAmountSum", MathUtils.formatToNumber(teamAmount));
        //团队新增
        int agentAddCount = agentService.queryAgentAddCount(agentId, type, 2);
        map.put("agentAddCount", agentAddCount);
        //商户报备新增
        int merchantAddCount = merchantService.queryMerchantCount(agentId, type, 2);
        map.put("merchantAddCount", merchantAddCount);
        //团队采购
        int byTerminalCount = tranOrderService.queryByTerminalCount(agentId, type, 2);
        map.put("byTerminalCount", byTerminalCount);
        //团队激活
        int terminalActCount = terminalInfoService.queryActivationCount(agentId, type, 2);
        map.put("terminalActCount", terminalActCount);
        return map;
    }

    @Override
    public List<String> queryTranAndSumList(String sn) {
        return baseMapper.queryTranAndSumList(sn);
    }

    @Override
    public Map<String, String> acceptKaYou(String flowNo, String timeStamp, String acceptKey, String sign, AcceptKaYouDTO acceptKaYouDTO) {
        //校验参数 略

        Map<String, String> map = new HashMap<>();
        //返回成功
        map.put("resultCode", "00");

        String transType = acceptKaYouDTO.getTransType();
        String amount = acceptKaYouDTO.getAmount();
        String orderNo = acceptKaYouDTO.getOrderNo();
        String posSn = acceptKaYouDTO.getPosSn();
        String posCati = acceptKaYouDTO.getPosCati();
        String status = acceptKaYouDTO.getStatus();
        Date completeTime = acceptKaYouDTO.getCompleteTime();


        System.out.println("sn:" + posSn);
        System.out.println("code:" + posCati);
        System.out.println("date:" + completeTime);
        System.out.println("amount:" + amount);

        //只需要交易类型PURCHASE 交易状态SUCCESS成功
        if (StringUtils.equals(transType, "PURCHASE") && StringUtils.equals(status, "SUCCESS")) {
            //查询终端号是否存在
            TerTerminalInfo terTerminalInfo = terminalInfoService.queryTerminalBySn(posSn);
            //查询交易是否存在
            TransactionInput transactionInput = transactionInputService.selectById(orderNo);

            if (terTerminalInfo != null) {
                System.out.println("----------------------------");
                System.out.println("sn:" + posSn);
                System.out.println("code:" + posCati);
                System.out.println("date:" + completeTime);
                System.out.println("amount:" + amount);

                if (transactionInput == null) {
                    //判断终端号是否相同，不同则修改
                    if (!StringUtils.equals(posCati, terTerminalInfo.getMerchantCode())) {
                        terTerminalInfo.setMerchantCode(posCati);
                        terminalInfoService.updateById(terTerminalInfo);
                    }

                    //导入交易
                    TranTransactionInfo info = new TranTransactionInfo();

                    info.setAmount(new BigDecimal(amount));
                    info.setIsBenefited(0);
                    info.setTerminalType(terTerminalInfo.getTerminalType());
                    info.setDeptId(terTerminalInfo.getDeptId());
                    info.setMerchantCode(posCati);
                    info.setIsVip("否");
                    info.setTransactionDate(completeTime);
                    info.setCreateDate(new Date());
                    info.setKaolaType(1);
                    info.setSn(posSn);
                    baseMapper.insert(info);

                    transactionInput.setOrderId(orderNo);
                    transactionInput.setCreateDate(new Date());
                    transactionInputService.insert(transactionInput);

                }

            }

        }
        return map;
    }

    @Override
    public void addTransactionShanyin(String sessionId, Long accountId, String expInfo) {

        try {
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            //获取系统的昨天日期
            String date = StringUtil.getDifferDate(-1);
            Date toDate = DateUtils.stringToDate(date, DateUtils.DATE_PATTERN);
            //根据session访问闪银网站
            String requestUrl = "https://sympos.umfintech.com/mpos-web/trade!currAllBig.action?input_select=input_select";
            String repost = HttpClean.httpsRequest(requestUrl, "POST", "pageInfo.currentPage=1&pageInfo.pageSize=9999&tradeWaterDto.userTel=&tradeWaterDto.equipCsn=&tradeWaterDto.tradeWaterId=&tradeWaterDto.cardCode=&tradeWaterDto.tradeAgentCode=&tradeWaterDto.tradeBeginDate=" + DateUtils.format(toDate, "yyyyMMdd") + "&tradeWaterDto.tradeEndDate=" + DateUtils.format(toDate, "yyyyMMdd") + "&tradeWaterDto.settleDateFrom=&tradeWaterDto.settleDateTo=&tradeWaterDto.userId=&tradeWaterDto.userTradeAddress=&tradeWaterDto.tradeStatus=1&tradeWaterDto.checkoutType=&tradeWaterDto.isPelFee=&tradeWaterDto.moduleType=&tradeWaterDto.usertaskName=", sessionId);
            Document doc2 = Jsoup.parse(repost);

            Element elementById = doc2.getElementById("RefBasCommercialDocTable");

            Elements byTag = elementById.getElementsByTag("tr");


            for (Element element : byTag) {

                if (element.toString().contains("总额")) {
                    continue;
                }

                Elements tds = element.getElementsByTag("td");
                String rateStr = tds.get(14).text();
                String merchantCode = tds.get(3).text();
                if (rateStr.contains("云闪付")) {
                    continue;
                }

                String amount = tds.get(11).text();

                TerTerminalInfo terminal = terminalInfoService.queryTerminalByMCode(merchantCode);

                if (terminal != null) {
                    //累计添加交易笔数
                    totalNumber++;
                    //累计添加交易总额
                    totalTransaction = totalTransaction.add(new BigDecimal(amount));

                    //录入交易
                    TranTransactionInfo t = new TranTransactionInfo();
                    t.setAmount(new BigDecimal(amount));
                    t.setCreateDate(new Date());
                    t.setDeptId(terminal.getDeptId());
                    t.setIsVip("否");
                    t.setTerminalType(terminal.getTerminalType());
                    t.setMerchantCode(terminal.getMerchantCode());
                    t.setSn(terminal.getSn());
                    t.setTransactionDate(toDate);
                    baseMapper.insert(t);
                }


            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo(expInfo + "-" + "-成功");
            log.setAccountId(accountId);
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            insertTerLog(log);
        } catch (Exception e) {
            insertFailTerLog(expInfo + "-" + e.getMessage(), accountId);
        }


    }

    @Override
    public void benefitByMerchant(SysDept sysDept, String benefitDateStr) {

        Date benefitDate = DateUtils.stringToDate(benefitDateStr, DateUtils.DATE_PATTERN);
        //分润等级
        SysLvRate lvRate;
        //机器每天分润对象
        TranTerBenefitDay benefitDay;
        //机器分润详情对象
        TranTerBenefitInfo benefitInfo;
        //单机器总交易量
        BigDecimal allTranAmount;
        //单机器总分润
        BigDecimal allTranBenefit;
        //单次分润量
        BigDecimal benefitAmount;
        //合伙人
        SysAgent agent;
        //查出所有已报备的机器
        List<TerMerchantReport> list = merchantService.queryAllMerchantList(sysDept.getDeptId());

        for (TerMerchantReport terMerchantReport : list) {

            //查询报备机器的昨日交易
            List<TranTransactionInfo> tranList = queryYesterdayListBySn(terMerchantReport.getSn(), benefitDateStr, sysDept.getDeptId());
            //没有交易则核实机器交易记录,距离报备记录5天无交易则删除报备信息
            if (tranList == null || tranList.size() == 0) {
                merchantService.handleNoTranMer(terMerchantReport);
                continue;
            }
            //生成唯一id
            String snBenefitId = tranTerBenefitDayService.verifyBenefitId(StringUtil.getDateString(4));

            allTranAmount = new BigDecimal("0.00");
            allTranBenefit = new BigDecimal("0.00");

            agent = agentService.queryAgentById(terMerchantReport.getAgentId());

            TerTerminalInfo terminalInfo = terminalInfoService.queryTerminalBySn(terMerchantReport.getSn());

            //计算分润
            for (TranTransactionInfo tranTransactionInfo : tranList) {

                lvRate = lvRateService.getSysLvRate(tranTransactionInfo, agent.getAgentId());

                if (lvRate == null) {
                    log.info("-----" + tranTransactionInfo.getTransactionId() + "---" + agent.getAgentId() + "----未查询到分润等级--------------");
                    continue;
                }

                //如果是用户宝的机器，扣除一定的分润
                BigDecimal rate = lvRateService.getRateByYhb(agent.getAgentId(), terminalInfo, tranTransactionInfo, lvRate.getRate());

                //计算出分润,直接取两位小数
                benefitAmount = rate.multiply(tranTransactionInfo.getAmount()).divide(DIVIDENUM);

                //计算总交易
                allTranAmount = tranTransactionInfo.getAmount().add(allTranAmount);
                //计算总分润
                allTranBenefit = benefitAmount.add(allTranBenefit);
                //存入机器相关分润详情
                benefitInfo = tranTerBenefitInfoService.addTranTerBenefitInfo(benefitAmount, terMerchantReport, snBenefitId, tranTransactionInfo);

                benefitDayService.addSelfBenefitDay(tranTransactionInfo, benefitAmount, agent);

                agentInfoService.addAmount(agent.getAgentId(), benefitAmount);

                tranTransactionInfo.setIsBenefited(1);

                updateById(tranTransactionInfo);

                benefitTeam(tranTransactionInfo, terMerchantReport, benefitInfo);
            }
            benefitDay = new TranTerBenefitDay();

            benefitDay.setDeptId(terMerchantReport.getDeptId());

            benefitDay.setTerBenefitId(snBenefitId);
            //存入分润时间
            benefitDay.setBenefitDate(DateUtils.format(benefitDate, DateUtils.DATE_PATTERN));
            //存入sn
            benefitDay.setSn(terMerchantReport.getSn());
            //报备人
            benefitDay.setOwnerId(agent.getAgentId());
            //创建时间
            benefitDay.setCreateDate(new Date());
            //存入交易量
            benefitDay.setAllTranAmount(allTranAmount);
            //存入交易
            benefitDay.setAllBenefitAmount(allTranBenefit);
            tranTerBenefitDayService.insertTranTerBenefitDay(benefitDay);
        }
    }

    @Override
    public List<Map<String, Object>> queryTranByAgentAndMonth(Long agentId, String s) {
        List<Map<String,Object>> list=baseMapper.queryTranByAgentGroup(agentId,s);
        return list;
    }

    @Override
    public List<Map<String, Object>> querySumTranByAgentAndMonth(Long agentId, String s) {

        return  baseMapper.querySumTranByAgentGroup(agentId,s);
    }

    @Override
    public BigDecimal querySumTran(Long agentId, String month) {
        return baseMapper.querySumTran(agentId,month);
    }


    private void benefitTeam(TranTransactionInfo tranTransactionInfo, TerMerchantReport terMerchantReport, TranTerBenefitInfo benefitInfo) {
        //星脉联盟不管费率类型
        if (!tranTransactionInfo.getDeptId().equals(5L)) {
            if (tranTransactionInfo.getKaolaType().intValue() == 2) {
                return;
            }
        }

        List<PidRateView> list = lvRateService.queryPidRate(terMerchantReport.getAgentId(), tranTransactionInfo.getTerminalType(), tranTransactionInfo.getIsVip());

        SysLvRate agentLv = lvRateService.getSysLvRate(tranTransactionInfo, terMerchantReport.getAgentId());


        for (int i = 0; i <list.size() ; i++) {
            PidRateView v=list.get(i);

            Long pId = v.getAgentId();

            SysAgent agent = agentService.queryAgentById(pId);

            BigDecimal rate = v.getRate();
            BigDecimal subRate;
            if(i==0){
                subRate=agentLv.getRate();
            }else {
                subRate=list.get(i-1).getRate();
            }
            BigDecimal subtractRate = rate.subtract(subRate);

            BigDecimal teamBenefit = tranTransactionInfo.getAmount().multiply(subtractRate).divide(DIVIDENUM);

            teamBenefit = teamBenefit.compareTo(new BigDecimal("0.00")) == 1 ? teamBenefit : new BigDecimal("0.00");

            agentInfoService.addAmount(pId, teamBenefit);

            benefitDayService.updateTeamTranDay(agent, benefitInfo, teamBenefit, tranTransactionInfo.getTransactionDate());

        }


    }


}
